import {
  CheckOutlined,
  CheckSquareOutlined,
  DownloadOutlined,
  EnvironmentOutlined,
  UploadOutlined
} from '@ant-design/icons';
import {Button, Modal, Divider, Descriptions, Input, message, Select, Upload, Tag} from 'antd';
import React, {useState, useRef, useEffect, Component} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import {
  orderPage,
  getOrderDetail,
  getOrderDetailByIds,
  exportPrinter,
  changeMoney,
  updateOrder,
  confirmOrder,
  addDriverDetails,
  addDriverDetailsByOrders,
  exportDriverPrinter,
  confirmDriver,
  delDriver,
  delOrder,
  revokeOrder,
  delPayFile,
  getPayFiles,
  exportDriverDetails
} from './service';

import Access from '@/components/Access/Access';
import {PlusOutlined} from "@ant-design/icons";

import "./index.css";
import CreateForm from "./components/CreateForm";
import {saveFileAs} from "@/utils/utils";
import styles from "@/global.less";

import {storeBaseList} from "@/pages/OrderManagement/StoreOrder/service";
import defaultSetting from '@/../config/defaultSettings';

const {baseUrl} = defaultSetting;
const TableList = (props) => {
  const actionRef = useRef();
  const [count, setCount] = useState();
  const [record, setRecord] = useState({});
  const [details, setDetails] = useState({});
  const [orderDetail, handleOrderDetail] = useState(false);
  const [addDriverOrderDetail, handleAddDriverOrderDetail] = useState(false);

  const [outDetailsModal, handleOutDetailsModal] = useState(false);
  const [driverStockLoading, handleDriverStockLoading] = useState(false);
  const [mySelectedRowKeys, handleMySelectedRowKeys] = useState([]);
  const [mySelectedOrderKeys, handleMySelectedOrderKeys] = useState([]);
  const [storeArray, setStoreArray] = useState([]);
  const [mapStores, setMapStores] = useState([]);
  const [takeType, setTakeType] = useState(null);
  const [mapModalVisible, handleMapModalVisible] = useState(false);
  const [orderIds, setOrderIds] = useState([]);
  const [orderOutLoading, handleOrderOutLoading] = useState(false);
  const [confirmRecord, setConfirmRecord] = useState({});
  const getStore = () => {
    storeBaseList()
      .then((res) => {
        const {code} = res;
        code === 0 ? setStoreArray(res.data) : message.info(res.message);
      })
      .catch((err) => {
        console.log(err);
      });
  };
  useEffect(() => {
    getStore();
  }, []);

  let cancleRowKeys = [];
  let cancleOrderRowKeys = [];
  const onSelect = (record, selected) => {
    if (!selected) {
      cancleRowKeys = [record.purchaseId];
    }
  };
  const onSelectOrder = (record, selected) => {

    if (!selected) {
      cancleOrderRowKeys = [record.id];
    }
  };
  const onMulSelect = (selected, selectedRows, changeRows) => {
    if (!selected) {
      cancleRowKeys = changeRows.map((item) => item.purchaseId);
    }
  };
  const onOrderMulSelect = (selected, selectedRows, changeRows) => {
    if (!selected) {
      cancleOrderRowKeys = changeRows.map((item) => item.id);
    }
  };
  const onChange = (selectedRowKeys, selectedRows) => {
    if (cancleRowKeys.length) {
      const keys = mySelectedRowKeys.filter((item) => !cancleRowKeys.includes(item));
      handleMySelectedRowKeys(keys);
      cancleRowKeys = [];
    } else {
      handleMySelectedRowKeys([...new Set(mySelectedRowKeys.concat(selectedRowKeys))]);
    }
  };
  const onChangeOrder = (selectedRowKeys, selectedRows) => {
    if (cancleOrderRowKeys.length) {
      const keys = mySelectedOrderKeys.filter((item) => !cancleOrderRowKeys.includes(item));
      handleMySelectedOrderKeys(keys);
      cancleOrderRowKeys = [];
    } else {
      handleMySelectedOrderKeys([...new Set(mySelectedOrderKeys.concat(selectedRowKeys))]);
    }
  };
  const columns = [
    {
      title: '店铺',
      dataIndex: 'storeIds',
      hideInTable: true,
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <Select
            placeholder="请选择店铺"
            showSearch
            filterOption={(input, option) => {
              if (option.options) {
                option.options.map((data => {
                  return data.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                }));
                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              } else {
                return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              }
            }
            }
            mode="multiple"
            allowClear
          >
            {
              storeArray.map((item_, index) => {
                return (
                  <Select.OptGroup label={item_.posName}>
                    {
                      item_.stores.map((item_s, index_s) => {
                        return (
                          <Select.Option value={item_s.id} key={item_s.id}>
                            {item_s.name}
                          </Select.Option>
                        );
                      })
                    }
                  </Select.OptGroup>
                );
              })}
          </Select>
        );
      },
    },
    {
      title: '采购店铺',
      hideInSearch: true,
      render: (_, record) => {
        if (record.orderDetails && record.orderDetails[0]) {
          return <div>{record.orderDetails[0].storeName + '...'}</div>;
        } else {
          return <div>{''}</div>;
        }
      },
    },
    {
      title: '一级区域',
      dataIndex: 'regionParentName',
      render: (_, record) => {
        if (record.orderDetails && record.orderDetails[0]) {
          return <div>{record.orderDetails[0].deptParentName + '...'}</div>;
        } else {
          return <div>{''}</div>;
        }
      },
    },
    {
      title: '二级区域',
      dataIndex: 'regionName',
      hideInTable: true
    },
    {
      title: '出库单号',
      dataIndex: 'number',
      hideInTable: true
    },
    {
      title: '采购产品',
      dataIndex: 'goodsName',
      hideInTable: true
    },
    {
      title: '采购产品',
      hideInSearch: true,
      render: (_, record) => {
        if (record.orderDetails && record.orderDetails[0] && record.orderDetails[0].drivers) {
          return <div>{record.orderDetails[0].drivers[0].goodsDetails[0].goodsName + '...'}</div>;
        } else {
          return <div>{''}</div>;
        }
      },
    },
    {
      title: '确认时间',
      dataIndex: 'createTime',
      hideInSearch: true,
    },
    {
      title: '收货方式',
      dataIndex: 'takeType',
      valueEnum: {
        false: {
          text: '仓库发货',
          status: 'Success',
        },
        true: {
          text: '自提',
          status: 'Error',
        },
      },
    },
    {
      title: '出库状态',
      dataIndex: 'confirm',
      valueEnum: {
        true: {
          text: '已确认',
          status: 'Success',
        },
        false: {
          text: '未确认',
          status: 'Error',
        },
      },
    },
    {
      title: '采购状态',
      dataIndex: 'purchaseStatus',
      hideInTable: true,
      valueEnum: {
        3: {
          text: '已分配',
          status: 'Success',
        },
        4: {
          text: '待收货',
          status: 'Error',
        },

        99: {
          text: '已驳回',
          status: 'Error',
        },
      },
    },
    {
      title: '司机',
      dataIndex: 'driver',
      hideInSearch: true,
      render: (_, record) => {
        let driverInfo = record.orderDetails[0]?.drivers[0];
        if (driverInfo?.id !== '0') {
          return <div>{driverInfo.driver ? driverInfo.driver : '' + '...'}</div>;
        }
        return <div>{''}</div>;
      },
    },
    {
      title: '车牌',
      dataIndex: 'carNum',
      hideInSearch: true,
      render: (_, record) => {
        let driverInfo = record.orderDetails[0]?.drivers[0];
        if (driverInfo?.id !== '0') {
          return <div>{driverInfo.carNum ? driverInfo.carNum : '' + '...'}</div>;
        }
        return <div>{''}</div>;
      },
    },
    {
      title: '运费',
      dataIndex: 'carMoney',
      hideInSearch: true,
      render: (_, record) => {
        let driverInfo = record.orderDetails[0]?.drivers[0];
        if (driverInfo?.id !== '0') {
          return <div>{driverInfo.carMoney ? driverInfo.carMoney : '' + '...'}</div>;
        }
        return <div>{''}</div>;
      },
    },
    {
      title: '电话',
      dataIndex: 'driverTel',
      hideInSearch: true,
      render: (_, record) => {
        let driverInfo = record.orderDetails[0]?.drivers[0];
        if (driverInfo?.id !== '0') {
          return <div>{driverInfo.driverTel ? driverInfo.driverTel : '' + '...'}</div>;
        }
        return <div>{''}</div>;
      },
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_, item) => {
        let hasDriver = false;
        if (item.orderDetails) {
          item.orderDetails.forEach(order => {
            hasDriver = order.drivers[0]?.id !== '0';
          })
        }

        return (
          <>
            <div style={{
              display: "flex",
              overflow: "hidden"
            }}>
              {
                (!item.takeType && !item.confirm && !hasDriver) ? (
                  <Access accessKey={"@unifyPurchase_delOrder"}>
                    <Button
                      type="primary"
                      danger
                      style={{
                        marginLeft: "10px"
                      }}
                      onClick={() => {
                        Modal.confirm({
                          title: '注意',
                          content: '确认是否撤回此出库订单',
                          onOk() {
                            let id = item.id;
                            delOrder({
                              id
                            }).then(res => {
                              if (res?.code === 0) {
                                message.info("撤销成功");
                              }
                              actionRef.current.reload();
                            })
                          },
                          onCancel() {
                          },
                        });
                      }}
                    >
                      撤销
                    </Button>
                  </Access>

                ) : null
              }
              {
                (item.takeType && !item.confirm && !hasDriver) ? (
                  <Access accessKey={"@unifyPurchase_revokeOrder"}>
                    <Button
                      type="primary"
                      danger
                      style={{
                        marginLeft: "10px"
                      }}
                      onClick={() => {
                        Modal.confirm({
                          title: '注意',
                          content: '确认是否撤回此出库订单',
                          onOk() {
                            let id = item.orderDetails[0].id;
                            revokeOrder({
                              id
                            }).then(res => {
                              if (res?.code === 0) {
                                message.info("撤销成功");
                              }
                              actionRef.current.reload();
                            })
                          },
                          onCancel() {
                          },
                        });
                      }}
                    >
                      撤销
                    </Button>
                  </Access>

                ) : null
              }

            </div>
          </>
        );
      },
    },
  ];

  const storeColumns = [
    {
      title: '店铺',
      dataIndex: 'storeName',
    },
    {
      title: '一级区域',
      dataIndex: 'deptParentName',
    },
    {
      title: '二级区域',
      dataIndex: 'deptName',
    },
    {
      title: '出库单号',
      dataIndex: 'number',
    },
    {
      title: '采购状态',
      dataIndex: 'status',
      valueEnum: {
        3: {
          text: '已分配',
          status: 'Error',
        },
        4: {
          text: '待收货',
          status: 'Error',
        },
        5: {
          text: '已出库',
          status: 'Error',
        },
        51: {
          text: '部分出库',
          status: 'Error',
        },
        6: {
          text: '调整中',
          status: 'Error',
        },
        7: {
          text: '审批中',
          status: 'Error',
        },
        9: {
          text: '已完成',
          status: 'Success',
        },
        99: {
          text: '已驳回',
          status: 'Error',
        },
      }
    },
    {
      title: '收货方式',
      dataIndex: 'takeType',
      valueEnum: {
        0: {
          text: '仓库发货',
          status: 'Success',
        },
        1: {
          text: '自提',
          status: 'Error',
        },
      },
    },
    {
      title: '收货地址',
      dataIndex: 'addr',
    },
    {
      title: '备注',
      dataIndex: 'remake',
      hideInSearch: true,
    }
  ];

  const detailColumns = storeColumns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_, item) => {

        return <>
          <div style={{
            display: "flex",
            overflow: "hidden"
          }}>
            {
              !item.takeType ? (
                <Access accessKey={"@unifyPurchase_address"}>
                  <Button
                    type="primary"
                    danger
                    style={{
                      marginLeft: "10px"
                    }}
                    onClick={(e) => {
                      if (item.takeLatitude && item.takeLongitude) {
                        let url = 'https://m.amap.com/share/index/lnglat=' + item.takeLongitude + ',' + item.takeLatitude;
                        navigator.clipboard.writeText(url);
                        message.info("收货地址链接生成成功！");
                      } else {
                        message.error("没有收货地址定位！");
                      }
                    }}
                  >
                    收货地址
                  </Button>
                </Access>

              ) : null
            }
            {/*{*/}
            {/*  (item.id !== '0' && item.takeType && item.status === 3) ? (*/}
            {/*    <>*/}
            {/*      <Access accessKey={"@unifyPurchase_confirmOrder"}>*/}
            {/*        <Button*/}
            {/*          type="primary"*/}
            {/*          danger*/}
            {/*          style={{*/}
            {/*            marginLeft: "10px"*/}
            {/*          }}*/}
            {/*          onClick={() => {*/}
            {/*            Modal.confirm({*/}
            {/*              title: '注意',*/}
            {/*              content: '确认是否已完成出库',*/}
            {/*              onOk() {*/}
            {/*                let id = item.id;*/}
            {/*                confirmOrder({*/}
            {/*                  id*/}
            {/*                }).then(res => {*/}
            {/*                  if (res?.code === 0) {*/}
            {/*                    message.info("确认成功");*/}
            {/*                  }*/}
            {/*                  actionRef.current.reload();*/}
            {/*                })*/}
            {/*              },*/}
            {/*              onCancel() {*/}
            {/*                handleOrderDetail(true);*/}
            {/*              },*/}
            {/*            });*/}
            {/*          }}*/}
            {/*        >*/}
            {/*          确认*/}
            {/*        </Button>*/}
            {/*      </Access>*/}


            {/*    </>*/}
            {/*  ) : null*/}
            {/*}*/}
          </div>
        </>;
      },
    },
  ]);

  const orderDetailColumns = [
    {
      title: '产品',
      dataIndex: 'goodsName',
      hideInSearch: true,
    },
    {
      title: '条码',
      dataIndex: 'barCode',
      hideInSearch: true,
    },
    {
      title: '采购数量',
      dataIndex: 'purchaseNumber',
      hideInSearch: true,
    },
    {
      title: '分配数量',
      dataIndex: 'outStock',
      hideInSearch: true,
    },
    {
      title: '库存',
      dataIndex: 'sysStock',
      hideInSearch: true,
    },
    {
      title: '承运数量',
      dataIndex: 'driverStock',
      hideInSearch: true,
    },
  ];
  const showConfirm = (record) => {
    Modal.info({
      title: '注意',
      okText: '确认',
      content: '确认要修改[' + record.goodsName + ']的本次承运数量为[' + record.tempStock + ']吗?',
      onOk() {
      },
      onCancel() {
      },
    });
  };
  const driverStockColumns = [
    {
      title: '产品',
      dataIndex: 'title',
      hideInSearch: true,
    },
    {
      title: '条码',
      dataIndex: 'barCode',
      hideInSearch: true,
    },
    {
      title: '已分配数量',
      dataIndex: 'outStock',
      hideInSearch: true,
    },
    {
      title: '重量(吨)',
      dataIndex: 'tonnage',
      hideInSearch: true,
    },
    {
      title: '库存',
      dataIndex: 'sysStock',
      hideInSearch: true,
    },
  ];
  const outStockColumns = [
    {
      title: '产品',
      dataIndex: 'goodsName',
      hideInSearch: true,
    },
    {
      title: '条码',
      dataIndex: 'barCode',
      hideInSearch: true,
    },
    {
      title: '已分配数量',
      dataIndex: 'outStock',
      hideInSearch: true,
    },
    {
      title: '库存',
      dataIndex: 'sysStock',
      hideInSearch: true,
    },
    {
      title: '承运数量',
      hideInSearch: true,
      dataIndex: 'driverStock',
      render: (dom, record) => {

        let flag = false;
        let curStock = record.outStock - record.driverStock;
        return <Input
          disabled={curStock <= 0}
          placeholder={curStock}
          onChange={(e) => {
            let inpStock = e.target.value;
            if (inpStock > curStock) {
              flag = false;
              message.info("承运数量大于已分配数量按分配数量计算!");
              return;
            }
            record.tempStock = inpStock;
            flag = true;
          }
          }
          onPressEnter={() => {
            if (record.tempStock && flag) {
              flag = false;
              showConfirm(record);
            }
          }
          }
          onBlur={() => {
            if (record.tempStock && flag) {
              flag = false;
              showConfirm(record)
            }
          }
          }
        />;
      },
    }
  ];

  const driverBaseColumns = [
    {
      title: '运费',
      dataIndex: 'carMoney',
      valueType: 'text',
    },
    {
      title: '结算账号',
      dataIndex: 'payment',
      valueType: 'text',
    },
    {
      title: '开户行',
      dataIndex: 'bank',
      valueType: 'text',
    },
    {
      title: '司机',
      dataIndex: 'driver',
      valueType: 'text',
    },
    {
      title: '车牌',
      dataIndex: 'carNum',
      valueType: 'text',
    },
    {
      title: '电话',
      dataIndex: 'driverTel',
      valueType: 'text',
    },
    {
      title: '身份证',
      dataIndex: 'driverCard',
      valueType: 'text',
    },

  ];

  const listDriverColumns = driverBaseColumns.concat([
    {
      title: '子单号',
      dataIndex: 'number',
    },
    {
      title: '出库状态',
      dataIndex: 'confirm',
      valueEnum: {
        false: {
          text: '未确认',
          status: 'Error',
        },
        true: {
          text: '已确认',
          status: 'Success',
        },
      },
    },
    {
      title: '付款状态',
      dataIndex: 'status',
      valueEnum: {
        0: {
          text: '未付款',
          status: 'Error',
        },
        1: {
          text: '申请中',
          status: 'Error',
        },
        2: {
          text: '已付款',
          status: 'Success',
        },
      },
    },
    {
      title: '发货备注',
      dataIndex: 'remake',
    },
    {
      title: '收货状态',
      dataIndex: 'inStockType',
      valueEnum: {
        0: {
          text: '未收货',
          status: 'Error',
        },
        1: {
          text: '收货有异议',
          status: 'Error',
        },
        2: {
          text: '收货无异议',
          status: 'Success',
        },
      },
    },
    {
      title: '收货备注',
      dataIndex: 'inStockRemake',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_, item) => {
        return <>
          <div style={{
            display: "flex",
            overflow: "hidden"
          }}>
            {
              item.id === '0' ? (
                <Access accessKey={"@unifyPurchase_exportPrinter"}>
                  <Button
                    type="primary"
                    style={{
                      marginLeft: "10px"
                    }}
                    onClick={() => {
                      let params = {
                        purchaseId: item.pid
                      };
                      Modal.confirm({
                        title: '请选择要生成的单据类型',
                        okText: '普通',
                        cancelText: '加长',
                        maskClosable:true,
                        onOk() {
                          params.type = "1";
                          exportPrinter(params).then(res => {
                            if (res) {
                              saveFileAs(res, '出库单');
                            }
                          })
                        },
                        onCancel(e) {
                          if (!e.triggerCancel){
                            params.type = "0";
                            e();
                            exportPrinter(params).then(res => {
                              if (res) {
                                saveFileAs(res, '出库单');
                              }
                            })
                          }
                        },
                      });
                    }}
                  >
                    出库单
                  </Button>
                </Access>

              ) : null
            }
            {
              (item.id !== '0' && !item.confirm) ? (
                <Access accessKey={"@unifyPurchase_confirmDriver"}>
                  <Button
                    type="primary"
                    style={{
                      marginLeft: "10px"
                    }}
                    onClick={() => {
                      setConfirmRecord(item);
                      handleOrderDetail(true);
                    }}
                  >
                    确认出库
                  </Button>
                </Access>

              ) : null
            }
            {
              (item.id !== '0' && !item.confirm) ? (
                <Access accessKey={"@unifyPurchase_delDriver"}>
                  <Button
                    type="primary"
                    danger
                    style={{
                      marginLeft: "10px"
                    }}
                    onClick={() => {
                      Modal.confirm({
                        title: '注意',
                        content: '确定要撤销此承运信息?',
                        onOk() {
                          let id = item.id;
                          delDriver({
                            id
                          }).then(res => {
                            if (res?.code === 0) {
                              message.info("撤销成功");
                            }
                            actionRef.current.reload();
                          })

                        },
                        onCancel() {
                        },
                      });
                    }}
                  >
                    撤销
                  </Button>
                </Access>

              ) : null
            }
            {
              (item.id !== '0' && item.confirm && item.status === 0 && item.carMoney > 0) ? (
                <Access accessKey={"@unifyPurchase_changeMoney"}>
                  <Button
                    type="primary"
                    danger
                    style={{
                      marginLeft: "10px"
                    }}
                    onClick={() => {
                      getPayFiles({
                        id: item.id
                      }).then(res => {
                        let imgs = res.data?.map(img => {
                          return {
                            status: 'done',
                            uid: img.id,
                            name: img.id,
                            url: img.img,
                          }
                        });
                        showModal(imgs, item);
                      })
                    }}
                  >
                    申请付款
                  </Button>
                </Access>

              ) : null
            }
          </div>
        </>;
      },
    },
  ]);
  const addDriverColumns = driverBaseColumns.concat([
    {
      title: '备注',
      dataIndex: 'remake',
      valueType: 'text',
    },
  ]);
  const outDetailsColumns = [
    {
      title: '出库时间',
      dataIndex: 'purchaseDate',
      valueType: 'dateRange',
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1],
          };
        },
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '出库时间为必选项',
          },
        ],
      },
    },
    {
      title: '店铺',
      dataIndex: 'storeIds',
      hideInTable: true,
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <Select
            placeholder="请选择店铺"
            showSearch
            filterOption={(input, option) => {
              if (option.options) {
                option.options.map((data => {
                  return data.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                }));
                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              } else {
                return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              }
            }
            }
            mode="multiple"
            allowClear
          >
            {
              storeArray.map((item_, index) => {
                return (
                  <Select.OptGroup label={item_.posName}>
                    {
                      item_.stores.map((item_s, index_s) => {
                        return (
                          <Select.Option value={item_s.id} key={item_s.id}>
                            {item_s.name}
                          </Select.Option>
                        );
                      })
                    }
                  </Select.OptGroup>
                );
              })}
          </Select>
        );
      },
    },
  ];
  const goodsDetailRender = (e) => {
    return <>
      <ProTable
        rowKey={r => r.id}
        scroll={{x: 1400}}
        bordered
        dataSource={e.goodsDetails}
        search={false}
        toolBarRender={false}
        pagination={false}
        columns={orderDetailColumns}
      />
    </>
  };
  const driverDetailRender = (e) => {
    return <>
      <ProTable
        rowKey={r => r.id}
        scroll={{x: 1400}}
        bordered
        dataSource={e.drivers}
        search={false}
        toolBarRender={false}
        pagination={false}
        columns={listDriverColumns}
        expandedRowRender={goodsDetailRender}
      />
    </>;

  };
  const detailRender = (e) => {
    return <>
      <ProTable
        rowKey={r => r.id}
        scroll={{x: 1400}}
        bordered
        dataSource={e.orderDetails}
        search={false}
        toolBarRender={false}
        pagination={false}
        columns={detailColumns}
        expandedRowRender={driverDetailRender}
      />
    </>
  };
  const outStockRender = (e) => {
    return <>
      <ProTable
        rowKey={r => r.key}
        scroll={{x: 1400}}
        bordered
        dataSource={e.details}
        search={false}
        toolBarRender={false}
        pagination={false}
        columns={driverStockColumns}
      />
    </>
  };

  const showModal = (fileList, item) => {
    let newFileList = [];
    if (fileList && fileList.length > 0) {
      newFileList = newFileList.concat(fileList);
    }
    let handlePayUploadChange = (info) => {
      if (info.file.status === 'uploading') {
        return;
      }
      if (info.file.status === 'error') {
        message.error("文件上传失败");
      }
      newFileList = [...info.fileList];
    };
    let handleRemove = (file) => {
      return delPayFile({
        id: file.name
      }).then((res) => {
      })
    };
    let payMoney = item.carMoney;
    Modal.info({
      title: '请确认付款金额',
      okText: '提交',
      closable: true,
      content: (
        <>
          <div>
            <Input placeholder="修改运费金额" defaultValue={payMoney} onChange={(e) => {
              payMoney = e.target.value;
            }}/>
          </div>
          <div>
            <Upload
              name="file"
              action={() => {
                return `${baseUrl}supplyChain/driver/payFile`;
              }}
              listType="picture-card"
              defaultFileList={newFileList}
              onChange={handlePayUploadChange}
              onRemove={handleRemove}
              data={{driverId: item.id}}
              headers={{token: sessionStorage.getItem('token'), type: 'ADMIN'}}
            >
              {newFileList.length >= 5 ? null : (
                <div>
                  <PlusOutlined/>
                  <div style={{marginTop: 8}}>签收凭证</div>
                </div>
              )}
            </Upload>

          </div>
        </>
      ),
      onOk() {
        changeMoney({
          id: item.id,
          carMoney: payMoney
        }).then(res => {
          if (res?.code === 0) message.info("已发起付款申请");
          actionRef.current.reload();
        })
      },
    });
  };

  const alertRender = ({selectedRowKeys, selectedRows, onCleanSelected}) => {
    let details = selectedRows.map(row => {
      return row.orderDetails.map(order => order.drivers.map(driver => driver.goodsDetails).reduce((preVal, currVal) => preVal.concat(currVal), [])).reduce((preVal, currVal) => preVal.concat(currVal), []);
    }).reduce((preVal, currVal) => preVal.concat(currVal), []);
    let tempMap = new Map();
    details.forEach(detail => {
      if (tempMap.has(detail.goodsName)) {
        let temp = tempMap.get(detail.goodsName);
        temp.value = temp.value + detail.purchaseNumber;
        tempMap.set(detail.goodsName, temp)
      } else {
        tempMap.set(detail.goodsName, {
          value: detail.purchaseNumber,
          sysStock: detail.sysStock,
          robStock: detail.robStock
        })
      }
    });

    let tempList = [];
    tempMap.forEach((v, k) => {
      tempList.push({
        v, k
      })
    });
    return (
      <>
        预览:
        {
          tempList.map(({v, k}) => {
            return (
              <div>
                <Tag color="green">采购产品：{k}</Tag>
                <Tag color="red">采购数：{v.value}</Tag>
                {
                  v.sysStock ? <Tag color="blue">库存：{v.sysStock}</Tag> : null
                }
                {
                  v.robStock ? <Tag color="blue">已占：{v.robStock}</Tag> : null
                }
              </div>
            )
          })
        }
      </>
    );
  };


  const getOrderByIds = (ids) => {
    setOrderIds(ids);
    getOrderDetailByIds({
      ids
    }).then(res => {

      let details = res.data;
      setDetails(details);
      let stores = details.details;
      if (stores) {
        handleMySelectedOrderKeys(ids);
      }
      handleAddDriverOrderDetail(true);
    });
  };

  const alertOptionRender = ({selectedRowKeys, selectedRows, onCleanSelected}) => {
    return <>
      <div>
        <Access accessKey={"@unifyPurchase_addDriver"}>
          <Button
            key="approveBtn"
            onClick={() => {
              let ids = mySelectedOrderKeys ? mySelectedOrderKeys : selectedRows.map(data => data.id);
              getOrderByIds(ids);
            }}
          >
            <CheckSquareOutlined/>添加司机
          </Button>
        </Access>

      </div>
    </>
  };

  return (
    <PageContainer>
      <ProTable
        headerTitle="出库列表"
        actionRef={actionRef}
        rowKey={r => r.id}
        search={{
          defaultCollapsed: false,
          labelWidth: '80',
          defaultColsNumber: 3,
          span: 4
        }}
        scroll={{x: 1400}}
        bordered
        request={(params, sorter, filter) => orderPage({...params, sorter, filter})}
        postData={(payload) => {
          const {list, total} = payload;
          setCount(total);
          return list || [];
        }}
        toolBarRender={() => [
          <Access accessKey={"@driver_details_export"}>
            <Button
              key="driver_details_export"
              type="primary"
              onClick={() => {
                handleOutDetailsModal(true);
              }}
            >
              <DownloadOutlined/> 导出出库列表
            </Button>
          </Access>,

        ]}
        columns={columns}
        expandedRowRender={detailRender}
        defaultExpandAllRows
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        rowSelection={{
          fixed: true,
          selectedRowKeys: mySelectedOrderKeys,
          onSelect: onSelectOrder,
          onSelectMultiple: onOrderMulSelect,
          onSelectAll: onOrderMulSelect,
          onChange: onChangeOrder,
          getCheckboxProps: record => {
            return {
              disabled: false
            };
          },
        }}
        tableAlertRender={alertRender}
        tableAlertOptionRender={alertOptionRender}
        footer={() => {
          return (
            <div key="settleFooter" style={{color: 'red'}}>
              <span>说明：</span>
              <div>* 【确认出库】表示货品已从仓库发出，出库后该流程不可撤销，如有退货走退货流程!</div>
              <div>* 【出库单据】唯一性以店铺单次采购(自提)或单个司机(发货)为依据</div>
              <div>* 【未确认出库订单】均可打回到上一个流程</div>
              <div>* 【运费付款】收货自动发起，有异议可修改并重新发起</div>
            </div>
          );
        }}
      />


      <CreateForm width={1300}
                  onCancel={() => handleOrderDetail(false)}
                  modalVisible={orderDetail}
                  btn_view={(
                    <div className={styles.footer_btn}>
                      <Button danger type="primary" onClick={() => {
                        handleOrderDetail(false)
                      }}>
                        取消
                      </Button>
                      <Button loading={orderOutLoading} type="primary" onClick={() => {
                        handleOrderOutLoading(true);
                        let id = confirmRecord.id;
                        let details = confirmRecord.goodsDetails.map(detail => {
                          return {
                            detailId: detail.id,
                            driverId: id,
                            goodsName: detail.goodsName,
                            orderStock: detail.outStock,
                            outStock: detail.tempStock ? detail.tempStock : detail.outStock - detail.driverStock
                          };
                        });

                        confirmDriver({
                          id, details
                        }).then(res => {
                          if (res?.code === 0) {
                            message.info("确认成功");
                          }
                          handleOrderOutLoading(false);
                          handleOrderDetail(false);
                          actionRef.current.reload();
                        })
                      }}>
                        提交
                      </Button>
                    </div>
                  )}
      >
        <Divider orientation="left">出库详情</Divider>

        <ProTable
          headerTitle="采购详情列表"
          rowKey={r => {
            return r.id;
          }}
          scroll={{x: 1400}}
          bordered
          dataSource={confirmRecord.goodsDetails}
          search={false}
          toolBarRender={false}
          pagination={false}
          columns={outStockColumns}
        />

      </CreateForm>


      <CreateForm width={1300} onCancel={() => handleAddDriverOrderDetail(false)} modalVisible={addDriverOrderDetail}
                  btn_view={false}>
        <div style={{width: '100%', height: '100%'}}>
          <Divider orientation="left">出库详情</Divider>

          <ProTable
            headerTitle="采购详情列表"
            rowKey={r => {
              return r.orderId;
            }}
            scroll={{x: 1400}}
            bordered
            dataSource={details.details}
            search={false}
            toolBarRender={false}
            pagination={false}
            columns={storeColumns}
            expandedRowRender={outStockRender}
            defaultExpandAllRows
          />
          <Divider orientation="left">司机详情</Divider>
          <ProTable
            loading={driverStockLoading}
            className={styles.formModal}
            onSubmit={async (value) => {
              if (mySelectedOrderKeys.length > 0) {
                handleDriverStockLoading(true);
                let detailsDataSource = details.details;
                let driverDetails = [];
                detailsDataSource.filter(data => mySelectedOrderKeys.includes(data.orderId)).forEach(data => {
                  data.details.forEach(detail => {
                    driverDetails.push({
                      storeId: data.storeId,
                      orderId: data.orderId,
                      detailId: detail.detailId,
                      outStock: detail.tempStock ? detail.tempStock : detail.outStock - detail.driverStock
                    })
                  });
                });
                let params = Object.assign(value, {details: driverDetails, ids: orderIds});
                addDriverDetailsByOrders(params).then(res => {
                  handleDriverStockLoading(false);
                  if (res?.code === 0) {
                    message.success("添加成功!");
                    handleAddDriverOrderDetail(false);
                    actionRef.current.reload();
                  }
                })
              } else {
                message.error("请选择承运货品!")
              }
            }}
            rowKey="id"
            bordered
            type="form"
            form={{
              layout: 'horizontal ',
              labelAlign: 'rihgt',
              labelCol: {span: 4},
              wrapperCol: {span: 12},
            }}
            columns={addDriverColumns}
          />
        </div>
      </CreateForm>
      <CreateForm
        title={'导出信息'}
        width={800}
        btn_view={null}
        onCancel={() => {
          handleOutDetailsModal(false);
        }}
        modalVisible={outDetailsModal}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={(value) => {
            handleOutDetailsModal(false);
            exportDriverDetails(value).then(res=>{
              if (res){
                saveFileAs(res, '采购记录');
              }
            })
          }}
          rowKey={r=>r.id}
          bordered
          type="form"
          columns={outDetailsColumns}
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: {span: 8},
            wrapperCol: {span: 24},
          }}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
